package middleware

import (
    "SmartSearch/internal/repositories"
    "SmartSearch/internal/responses"
    "SmartSearch/internal/utils/jwt"
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

const loginUrl = "/login"

type AuthMiddleware struct {
    UserRepository *repositories.UserRepository
}

func NewAuthMiddleware() *AuthMiddleware {
    return &AuthMiddleware{
        UserRepository: &repositories.UserRepository{},
    }
}

func (m *AuthMiddleware) AuthToken() gin.HandlerFunc {
    return func(c *gin.Context) {
        if loginUrl == c.Request.URL.Path || "/file/download" == c.Request.URL.Path {
            fmt.Println("白名单直接跳过...")
            c.Next()
        } else {
            // 获取并验证JWT
            token := c.GetHeader("Authorization")
            if len(token) == 0 {
                c.JSON(http.StatusOK, responses.GenFailResult("未授权"))
                c.Abort()
                return
            }
            userId, err := jwt.ExtractToken(token)
            if err != nil {
                c.JSON(http.StatusOK, responses.GenFailResult("授权已过期"))
                c.Abort()
                return
            }
            user := m.UserRepository.FindById(userId)
            c.Set("user", user)
            c.Next()
        }
    }
}
